#include <string.h>
#include "eep.h"
#include "multiple_cache.h"

#define INVALID_CACHE_PAGE_NUM	0xFF
#define INVALID_EEP_PAGE_NUM	0xFFFF

typedef struct _cache_page{
	byte_t cache[EEP_PAGE_SIZE];
}cache_page;


typedef struct _cache_item{
	byte_t next_cache_page_num;
	byte_t prev_cache_page_num;
	word_t eep_page_num;
}cache_item;


byte_t g_head_page_index;
cache_page g_cache_pages[MULTIPLE_CACHE_COUNT];
cache_item g_cache_items[MULTIPLE_CACHE_COUNT];

void multiple_cache_init()
{
	byte_t i;
	g_head_page_index = 0;
	memset(g_cache_pages, INVALID_CACHE_PAGE_NUM, sizeof(g_cache_pages));
	memset(g_cache_items, INVALID_CACHE_PAGE_NUM, sizeof(g_cache_items));
	for (i = 0; i < MULTIPLE_CACHE_COUNT; ++i)
	{
		g_cache_items[i].next_cache_page_num = i + 1;
		g_cache_items[i].prev_cache_page_num = i - 1;
	}
	g_cache_items[MULTIPLE_CACHE_COUNT - 1].next_cache_page_num = INVALID_CACHE_PAGE_NUM;
}

void multiple_cache_hit(byte_t index)
{
	if (index != g_head_page_index)
	{
		byte_t prev_index = g_cache_items[index].prev_cache_page_num;
		byte_t next_index = g_cache_items[index].next_cache_page_num;
		g_cache_items[prev_index].next_cache_page_num = g_cache_items[index].next_cache_page_num;
		if (prev_index != INVALID_CACHE_PAGE_NUM)
		{
			g_cache_items[next_index].prev_cache_page_num = g_cache_items[index].prev_cache_page_num;
		}
		g_cache_items[index].next_cache_page_num = g_head_page_index;
		g_cache_items[index].prev_cache_page_num = INVALID_CACHE_PAGE_NUM;
		g_cache_items[g_head_page_index].prev_cache_page_num = index;
		g_head_page_index = index;
	}
}

